package com.zqxq.lottery.service.sys.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zqxq.common.utils.*;
import com.zqxq.lottery.common.constant.HuaYangConstant;
import com.zqxq.lottery.config.ApiJiSuConfig;
import com.zqxq.lottery.config.YmlConfig;
import com.zqxq.lottery.entity.api.jisu.CaiPiao;
import com.zqxq.lottery.entity.bo.sys.LotteryHnumBO;
import com.zqxq.lottery.entity.enums.LotteryIdEnum;
import com.zqxq.lottery.entity.o2o.sys.LotteryHnumO2O;
import com.zqxq.lottery.entity.o2o.sys.LotteryKindO2O;
import com.zqxq.lottery.entity.po.order.UserOrderPO;
import com.zqxq.lottery.entity.po.sys.LotteryHnumPO;
import com.zqxq.lottery.entity.po.sys.LotteryKindPO;
import com.zqxq.lottery.entity.vo.sys.LotteryHnumVO;
import com.zqxq.lottery.entity.vo.sys.LotteryKindVO;
import com.zqxq.lottery.mapper.order.UserOrderBetMapper;
import com.zqxq.lottery.mapper.order.UserOrderMapper;
import com.zqxq.lottery.mapper.sys.LotteryHnumMapper;
import com.zqxq.lottery.mapper.sys.LotteryKindMapper;
import com.zqxq.lottery.mq.Sender;
import com.zqxq.lottery.service.order.impl.UserOrderServiceImpl;
import com.zqxq.lottery.service.sys.ILotteryHnumService;
import com.zqxq.lottery.util.DateUtil;
import com.zqxq.lottery.util.JPushUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service
@Slf4j
public class LotteryHnumServiceImpl extends ServiceImpl<LotteryHnumMapper, LotteryHnumPO> implements ILotteryHnumService {

    private static String[] timeStrSSQ = {" 21:30:00"," 20:00:00"};
    private static String[] timeStrDLT = {" 20:45:00"," 20:00:00"};
    private static String[] timeStrFC = {" 21:30:00"," 20:00:00"};
    private static String[] timeStrPL = {" 20:45:00"," 20:00:00"};
    private static String[] timeStrQXC = {" 20:45:00"," 20:00:00"};

    @Autowired
    private YmlConfig ymlConfig;
    @Autowired
    private LotteryKindMapper lotteryKindMapper;
    @Autowired
    private UserOrderMapper userOrderMapper;
    @Autowired
    private UserOrderServiceImpl userOrderServiceImpl;
    @Autowired
    private ApiJiSuConfig apiJiSuConfig;
    @Autowired
    private Sender sender;

    @Override
    public Page<LotteryHnumVO> queryPage(LotteryHnumBO search) throws Exception {
        Wrapper<LotteryHnumPO> wrapper = new EntityWrapper();
        if (null != search.getId())
            wrapper.eq("id", search.getId());
        if (null != search.getLotteryId())
            wrapper.eq("lottery_id", search.getLotteryId());
        if (StrUtils.isNotEmpty(search.getPeriod()))
            wrapper.eq("period", search.getPeriod());
        if (null != search.getStatus())
            wrapper.ge("status", search.getStatus());
        wrapper.orderBy("period", false);
        wrapper.orderBy("lottery_id");
        Page page = new Page(search.getPageNo(), search.getPageSize());
        List list = baseMapper.selectPage(page, wrapper);
        page.setRecords(LotteryHnumO2O.toVOList(list));
        return page;
    }

    @Override
    public List<LotteryKindVO> queryLastOpenList() throws Exception {
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("status", 1);
        wrapper.orderBy("sort");
        List<LotteryKindPO> polist = lotteryKindMapper.selectList(wrapper);
        List<LotteryKindVO> voList = new ArrayList();
        for (LotteryKindPO po : polist) {
            LotteryKindVO vo = LotteryKindO2O.toVO(po);
            LotteryHnumPO hNum = baseMapper.getTopOpenOne(po.getId());
            if (hNum != null) {
                vo.setBlueNum(hNum.getBlue_num());
                vo.setRedNum(hNum.getRed_num());
                vo.setLotteryTime(DispatcherUtils.parseDateTimeStr(hNum.getLottery_time()));
                vo.setPeriod(hNum.getPeriod());
                voList.add(vo);
            }
        }
        return voList;
    }

    @Override
    public LotteryHnumVO save(LotteryHnumVO vo) throws Exception {
        LotteryHnumPO po = LotteryHnumO2O.toPO(vo);
        if (StrUtils.isEmpty(vo.getId())) {
            Long id = ymlConfig.getPkId();
            vo.setId(id + "");
            po.setId(id);
            baseMapper.insert(po);
        } else {
            baseMapper.updateById(po);
        }
        return vo;
    }

    @Override
    public LotteryHnumVO saveDataFromJisuApi(Long lotteryId,String period) throws Exception {
        LotteryHnumPO lotteryHnum = null;
        if(StrUtils.isEmpty(period))
            lotteryHnum = baseMapper.getTopCloseOne(lotteryId);
        else{
            Wrapper wrapper = new EntityWrapper();
            wrapper.eq("lottery_id",lotteryId);
            wrapper.eq("period",period);
            wrapper.in("status",new Integer[]{2,3});
            List<LotteryHnumPO> list = baseMapper.selectList(wrapper);
            if(null != list && list.size()>0)
                lotteryHnum = list.get(0);
        }
        if(null != lotteryHnum){
            Map params = new HashMap();
            params.put("appkey",apiJiSuConfig.getAppKey());
            params.put("caipiaoid",lotteryHnum.getLottery_id());
            params.put("issueno",lotteryHnum.getPeriod());
            String data = HttpUtils.doPost(apiJiSuConfig.getOpenNumUrl(),params);
            log.info("{}_{}从极速 API同步开奖结果：{}",lotteryHnum.getLottery_id(),lotteryHnum.getPeriod(),data);
            syncDataFromJisuApi(data,lotteryHnum);
        }
        return LotteryHnumO2O.toVO(lotteryHnum);

    }

    private void syncDataFromJisuApi(String data,LotteryHnumPO po){
        JSONObject jsonObject = JSONObject.parseObject(data);
        if ("0".equals(jsonObject.getString("status"))) {
            CaiPiao caiPiao = jsonObject.getObject("result", CaiPiao.class);
            po.setRed_num(caiPiao.getNumber().replaceAll(" ", ","));
            po.setBlue_num(caiPiao.getRefernumber().replaceAll(" ", ","));
            po.setLottery_time(DateUtils.getDateByStr(caiPiao.getOpendate()));
            po.setDeadline_time(DateUtils.getDateByStr(caiPiao.getDeadline()));
            po.setSale_amount(BigDecimalUtils.getBigDecimal(caiPiao.getSaleamount()));
            po.setTotal_money(BigDecimalUtils.getBigDecimal(caiPiao.getTotalmoney()));
            po.setStatus(3);
            if(null != caiPiao.getPrize()&& caiPiao.getPrize().size()>0) {
                po.setStatus(4);
                //发起推送
                try{
                    String pushMsg = "";
                    if (po.getLottery_id() == 11L)
                        pushMsg = "双色球今晚开奖结果 "+po.getRed_num()+"|"+po.getBlue_num();
                    if (po.getLottery_id() == 14L)
                        pushMsg = "大乐透今晚开奖结果 "+po.getRed_num()+"|"+po.getBlue_num();
                    if (StrUtils.isNotEmpty(pushMsg)) {
//                        sender.send(HuaYangConstant.MQ_PUSH_LOTTERY_RESULT, pushMsg, 1);
//                        Map<String, Object> map = JPushUtil.pushToAll(pushMsg);
//                        log.info("开奖推送结果map:" + JSONObject.toJSONString(map));
                    }
                }catch (Exception e){
                    log.info("send ERROR:",e);
                }

            }
            po.setApi_result(data);
            baseMapper.updateById(po);
        }
    }

    @Override
    public Boolean checkLotteryCanSale(Long lotteryId, String period) throws Exception {
        Map params = new HashMap();
        params.put("lotteryId", lotteryId);
        params.put("period", period);
        int num = baseMapper.checkLotteryCanSale(params);
        if (num > 0)
            return true;
        return false;
    }

    @Override
    public LotteryHnumVO addLotteryHnum(Long lotteryId) throws Exception {
        LotteryHnumPO po = baseMapper.getTopOne(lotteryId);

        if (null != po && null != po.getLottery_time()) {
            po = getNextOpen(po);
            if (null != po) {
                po.setId(ymlConfig.getPkId());
                po.setStatus(1);
                baseMapper.insert(po);
                return LotteryHnumO2O.toVO(po);
            }
        }
        return null;
    }

    //插入下一期竞猜开奖信息
    private LotteryHnumPO getNextOpen(LotteryHnumPO po) {
        LotteryIdEnum e = LotteryIdEnum.getEnumById(po.getLottery_id());
        Date nextDate = null;
        String lotteryTimeStr = "";
        String closeTimeStr = "";
        switch (e){
            case SSQ:
                lotteryTimeStr = timeStrSSQ[0];
                closeTimeStr = timeStrSSQ[1];
                nextDate = DateUtil.getNextOpenDateSSQ(po.getLottery_time());
                break;
            case DLT:
                lotteryTimeStr = timeStrDLT[0];
                closeTimeStr = timeStrDLT[1];
                nextDate = DateUtil.getNextOpenDateDLT(po.getLottery_time());
                break;
            case FC:
                lotteryTimeStr = timeStrFC[0];
                closeTimeStr = timeStrFC[1];
                nextDate = DateUtil.getNextOpenDateFCAndPL(po.getLottery_time());
                break;
            case PL:
                lotteryTimeStr = timeStrPL[0];
                closeTimeStr = timeStrPL[1];
                nextDate = DateUtil.getNextOpenDateFCAndPL(po.getLottery_time());
                break;
            case QXC:
                lotteryTimeStr = timeStrQXC[0];
                closeTimeStr = timeStrQXC[1];
                nextDate = DateUtil.getNextOpenDateQXC(po.getLottery_time());
        }
        if (nextDate != null){
            String dateStr = DateUtils.dateToStr(nextDate, "yyyy-MM-dd");
            po.setLottery_time(DateUtils.strToDate(dateStr + lotteryTimeStr));
            po.setClose_time(DateUtils.strToDate(dateStr + closeTimeStr));
            Integer nextPeriod = DispatcherUtils.parseInteger(po.getPeriod()) + 1;
            po.setPeriod(nextPeriod + "");
            po.setStatus(1);
            return po;
        }

        return null;
    }

    private LotteryHnumPO getNextOpenDLT(LotteryHnumPO po) {
        Date nextDate = DateUtil.getNextOpenDateDLT(po.getLottery_time());
        if (null != nextDate) {
            String dateStr = DateUtils.dateToStr(nextDate, "yyyy-MM-dd");
            po.setLottery_time(DateUtils.strToDate(dateStr + " 20:10:00"));
            po.setClose_time(DateUtils.strToDate(dateStr + " 20:00:00"));
            Integer nextPeriod = DispatcherUtils.parseInteger(po.getPeriod()) + 1;
            po.setPeriod(nextPeriod + "");
            po.setStatus(1);
            return po;
        }
        return null;
    }

    @Override
    @Transactional
    public LotteryHnumVO updateLotteryForClose(Long lotteryId) throws Exception {
        LotteryHnumVO newHnum = null;
        String now = DateUtils.dateToStr(DateUtils.addDay(new Date(),1),"yyyy-MM-dd");
        Map params = new HashMap();
        params.put("now",now);
        params.put("lotteryId",lotteryId);
        List<LotteryHnumPO> list = baseMapper.forClose(params);
        int t = 1;
        for(LotteryHnumPO po: list){
            po.setStatus(2);
            if(t==1){
                newHnum = addLotteryHnum(lotteryId);
            }
            //1、关闭未支付订单
            userOrderMapper.updateOrderForClose(po);
            //userOrderMapper.updateOrderBetForClose(po);
            //2、取消已支付未出票订单
            /*List<UserOrderPO> orderList = userOrderMapper.queryAllOrderForCancel(po);
            for(UserOrderPO order:orderList){
                userOrderServiceImpl.updateOrderCancel(order);
                //userOrderMapper.updateOrderBetCancel(order);
            }*/
            baseMapper.updateById(po);
            t++;
        }
        return newHnum;
    }

    @Override
    public LotteryHnumPO getLotteryHnumByPeriod(Long period) throws Exception {
        LotteryHnumPO LotteryHnumPO = null;
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("period", period);
        List<LotteryHnumPO> LotteryHnumPOList = baseMapper.selectList(wrapper);
        if (LotteryHnumPOList!=null && LotteryHnumPOList.size()!=0) {
            LotteryHnumPO = LotteryHnumPOList.get(0);
        }
        return LotteryHnumPO;
    }

}
